package com.hypo.business.controller;

import com.hypo.business.domain.GoodCategory;
import com.hypo.business.domain.Result;
import com.hypo.business.domain.vo.GoodVo;
import com.hypo.business.service.GoodCategoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/good")
@RequiredArgsConstructor
public class GoodCategoryController {
    private final GoodCategoryService goodCategoryService;

    /**
     * 查询所有
     */
    @GetMapping
    public Result list() {
        List<GoodCategory> all = goodCategoryService.list();
        if (CollectionUtils.isEmpty(all)) {
            return Result.error("查询错误");
        }
        return Result.success(goodCategoryService.find(all));
    }

    /**
     * 新增商品
     */
    @PostMapping
    public Result save(@RequestBody GoodVo vo) {
        GoodCategory goodCategory = new GoodCategory();
        if (vo.getId() != null) {
            vo.setParentId(vo.getId());
            vo.setId(null);
        } else {
            vo.setParentId(0);
        }
        BeanUtils.copyProperties(vo, goodCategory);
        goodCategory.setCreateTime(LocalDateTime.now());
        goodCategoryService.save(goodCategory);
        return Result.success();
    }

    /**
     * 修改
     */
    @PutMapping
    public Result update(@RequestBody GoodVo vo) {
        GoodCategory goodCategory = new GoodCategory();
        BeanUtils.copyProperties(vo, goodCategory);
        goodCategoryService.updateById(goodCategory);
        return Result.success();
    }

    /**
     * 删除
     */
    @DeleteMapping
    public Result delete(@RequestParam Integer id) {
        goodCategoryService.removeById(id);
        return Result.success();
    }
}
